import re
import numpy as np
import pandas as pd
import pymysql
import threading
from api.serial.detect import detect_sample
from detecter import settings


class Shouji_Chuanshu(threading.Thread):
    __instance = None

    def __init__(self, current_mould):
        super().__init__()
        self.setName('consumer')
        self.__running = threading.Event()
        self.current_mould = current_mould

    @classmethod
    def new_instance(cls, current_mould):
        cls.__instance = Shouji_Chuanshu(current_mould)
        return cls.__instance

    def begin(self):
        if not self.is_alive():
            self.__running.set()
            self.setDaemon(False)  # 不设置守护线程, 就算websocket挂了也继续收集数据,处理数据, 存入临时文件中, 直到停止本工单才算停止此线程
            self.start()

    def run(self):
        current_mould = self.current_mould
        portrait_result = current_mould.portrait_result
        sample_list = current_mould.producer.get_sample_list1()
        while self.__running.is_set():
            while len(sample_list) > 0:
                current_sample = sample_list.pop(0)
                sample_id = current_sample.id
                try:
                    shouji_chuanshu(sample_id, current_sample, current_mould, portrait_result, detect_sample)
                except:
                    # print('数据没有传输到mysql')
                    pass
        print('线程没有启动')


def table_exists(con, table_name):  # 这个函数用来判断表是否存在
    sql = "show tables;"
    con.execute(sql)
    tables = [con.fetchall()]
    table_list = re.findall('(\'.*?\')', str(tables))
    table_list = [re.sub("'", '', each) for each in table_list]
    if table_name in table_list:
        return 1  # 存在返回1
    else:
        return 0  # 不存在返回0


def shouji_chuanshu(sample_id, current_sample, current_mould, portrait_result, detect_sample):
    modo_code = str(current_mould.mould_code)
    jitai_code = settings.MACHINE_CODE
    zhouqi = ''
    yichanglv = ''
    time_start = ''
    time_end = ''
    all_zhengshu = ''

    zhusu_time_start = ''
    zhusu_time_end = ''
    zhusu_zhengshu = ''

    actual_pressure = ''
    actual_location = ''
    actual_speed = ''
    setting_pressure = ''
    setting_speed = ''

    shangjie_pressure = ''
    xiajie_pressure = ''
    portrait_location = ''
    portrait_pressure = ''
    portrait_speed = ''

    try:
        if sample_id < 51:
            yichanglv = '前50个样本异常率不计算'
        else:
            if portrait_result.is_result_safe:
                # 如果安全就进行检测
                detect_result = detect_sample(current_sample, portrait_result, isPostive=True)
                yichanglv = detect_result[5]
            else:
                yichanglv = '模拟特征中存在空值'
    except:
        yichanglv = '-1'

    try:
        dict = current_sample.get_userful_info_dic()
        time_start = dict['time_info'][0]
        time_end = dict['time_info'][1]
        all_zhengshu = dict['time_info'][2]
        zhusu_time_start = dict['time_info'][3]
        zhusu_time_end = dict['time_info'][4]
        zhusu_zhengshu = dict['time_info'][5]
        zhouqi = dict['time_info'][6]
        actual_pressure = str(dict['actual_pressure'])
        actual_location = str(dict['actual_location'])
        actual_speed = str(dict['actual_speed'])
        setting_pressure = str(dict['setting_pressure'])
        setting_speed = str(dict['setting_speed'])
    except:
        pass

    try:
        N, list_len, all_feat, actual_pressure_list, actual_location_list, actual_speed_list, setting_pressure_list, seg_points_list, id_list = \
            portrait_result.load_data_from_good_file(current_mould.good_file)
        portrait_actual_pressure = np.mean([i[:N] for i in actual_pressure_list if len(i) >= N], axis=0)
        portrait_actual_location = np.mean([i[:N] for i in actual_location_list if len(i) >= N], axis=0)
        portrait_actual_speed = np.mean([i[:N] for i in actual_speed_list if len(i) >= N], axis=0)
        portrait_location = str(portrait_actual_pressure.tolist())
        portrait_pressure = str(portrait_actual_location.tolist())  # 这里的location和pressure顺序弄反了
        portrait_speed = str(portrait_actual_speed.tolist())
        df = pd.DataFrame(actual_pressure_list)
        pd1 = df[[i for i in range(N)]]
        zuixiaozhi = pd1.apply(lambda x: x.min(), axis=0)
        zuidazhi = pd1.apply(lambda x: x.max(), axis=0)
        a = list(np.array(zuixiaozhi))
        a1 = [float(i) for i in a]
        b = list(np.array(zuidazhi))
        b1 = [float(i) for i in b]
        shangjie_pressure = str(b1)
        xiajie_pressure = str(a1)
    except:
        pass
    try:
        conn = pymysql.connect(host="192.168.6.92", user="root", port=3306, passwd="Hengde123", db="python_shuju", charset='utf8')
        cursor = conn.cursor()
        cursor.execute('use python_shuju')

        # 英文字母转小写
        modo_code = modo_code.lower()
        modo_code = modo_code.replace('-', '_')
        if table_exists(cursor, modo_code) != 1:
            cursor.execute("create table {} like 原始数据格式;".format(modo_code))

        sql = "insert into `{}`(modo_code,jitai_code ,zhouqi, yichanglv, " \
              "time_start, time_end,all_zhengshu," \
              " zhusu_time_start, zhusu_time_end,zhusu_zhengshu, " \
              "actual_pressure, actual_location,actual_speed," \
              " setting_pressure, shangjie_pressure, xiajie_pressure," \
              " portrait_location, portrait_pressure, portrait_speed, setting_speed) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)".format(
            modo_code)

        cursor.execute(sql, (modo_code, jitai_code, zhouqi, yichanglv, time_start, time_end,
                             all_zhengshu, zhusu_time_start, zhusu_time_end,
                             zhusu_zhengshu, actual_pressure, actual_location,
                             actual_speed, setting_pressure, shangjie_pressure,
                             xiajie_pressure, portrait_location, portrait_pressure, portrait_speed, setting_speed))
        # print('数据传输到mysql')
        # 执行SQL语句
        conn.commit()
        # 关闭光标对象
        cursor.close()
        # 关闭数据库连接
        conn.close()
    except Exception as e:
        # print('mysql连接异常或者传输数据失败:::', e)
        pass
